package com.ruike.alisurface.ui.settings;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.SlotBean;
import com.ruike.alisurface.https.MchApiHttp;
import com.ruike.alisurface.serialport.ShopInfoUtils;
import com.ruike.alisurface.ui.adapters.SlottestAdapter;
import com.ruike.alisurface.utils.GsonUtils;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.serialport.util.ByteUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


/**
 * 货道检测页
 */
public class SlotTest_Aty extends BaseAty {
    @BindView(R.id.goback_imgv)
    ImageView gobackImgv;
    @BindView(R.id.start_et)
    EditText startEt;
    @BindView(R.id.end_et)
    EditText endEt;
    @BindView(R.id.number_et)
    EditText numberEt;
    @BindView(R.id.make_sure_test)
    TextView makeSureTest;
    @BindView(R.id.Text_all)
    TextView TextAll;
    @BindView(R.id.slot_cycler)
    RecyclerView slotCycler;


    List<SlotBean> dataBeanList = new ArrayList<>();
    SlottestAdapter slottestAdapter;
    List<SlotBean> intervaldataBeanList = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.app_slot_test;
    }

    @Override
    protected void onStart() {
        super.onStart();
        Constant.isShopShipment = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        Constant.isShopShipment = false;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);
        gobackImgv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
//输完测试的货道以及转动的次数，点击确定按钮
        makeSureTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isTest) {
                    L.i("tjf=测试的货道=", "已经在测试货到了 不可点击了");
                    return;
                }
                try {
                    slotindex = 0;
                    slotNumber = 0;
                    slotType = 0;
                    count = 0;
                    TestSolt();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        TextAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isTest) {
                    L.i("tjf=测试的货道=", "已经在测试货到了 不可点击了");
                    return;
                }
                count = 0;
                isTest = true;
                showProgressDialog("正在测试所有货道，请等待......", true);
                putSlot(dataBeanList);
            }
        });
    }


    @Override
    protected void initData() {
      /*  for (int i = 1; i < 5; i++) {
            SlotBean slotBean = new SlotBean();
            slotBean.setIndex(i);
            slotBean.setSlottypeid(21001);
            slotBean.setCount(1);
            dataBeanList.add(slotBean);
        }*/
        MchApiHttp.getSlots(new ApiListener() {
            @Override
            public void onRequestStart(String requestUrl, int requestId) {

            }

            @Override
            public void onRequestComplete(String requestUrl, int requestId) {

            }

            @Override
            public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
                try {
                    String data = requestJson.optString("data");
                    dataBeanList.addAll(GsonUtils.jsonArrayToModelList(data, SlotBean.class));
                    slottestAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {


            }
        });

        slottestAdapter = new SlottestAdapter(this, dataBeanList);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 10);
        slotCycler.setLayoutManager(gridLayoutManager);
        slotCycler.setAdapter(slottestAdapter);
        slottestAdapter.setOnItemClickListenerr(new SlottestAdapter.OnItemClickListenerr() {
            @Override
            public void onGoodsSlotClick(int index) {
                if (isTest) {
                    L.i("tjf=测试的货道=", "已经在测试货到了 不可点击了");
                    return;
                }
                List<SlotBean> dataLists = new ArrayList<>();
                dataLists.add(dataBeanList.get(index));
                showProgressDialog("正在测试所选货道，请等待......", true);
                isTest = true;
                count = 0;
                putSlot(dataLists);
            }
        });

    }


    public void putSlot(List<SlotBean> slotList) {
        if (slotList.size() <= 0) {
            L.i("toshop", "货到信息没有");
            handler.sendEmptyMessage(3);
            return;
        }
        slotindex = slotList.get(count).getIndex();
        slotNumber = 1;
        slotType = slotList.get(count).getSlottypeid();
        ShopInfoUtils.getInstance().TodoShipmentSlot(slotList.get(count).getIndex(), slotList.get(count).getSlottypeid(), 1);
        count++;
        ShopInfoUtils.getInstance().setSlotCallBacK(new ShopInfoUtils.SlotCallBacK() {
            @Override
            public void onSlotSuccess(String resultDataStr, byte[] resultBytes) {
                slotSerialData(resultDataStr, resultBytes);
                ShopInfoUtils.getInstance().Timercancal();
                ShopInfoUtils.getInstance().analyzeSlotTest(resultBytes, slotType);
                L.i("SlotCallBac", "onSlotSuccess  商品出货完成 ==" + resultDataStr);
                if (count < slotList.size()) {
                    putSlot(slotList);
                } else {
                    L.i("toshop", "onSlotSuccess 整个商品出货完成 ");
                    handler.sendEmptyMessage(3);
                }
            }

            @Override
            public void onSlotFail(int slotindex) {
                for (SlotBean gbs : dataBeanList) {
                    if (gbs.getIndex() == slotindex) {
                        gbs.setTurnNumber(-1);
                    }
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        slottestAdapter.setData(dataBeanList);
                    }
                });
                if (count < slotList.size()) {
                    putSlot(slotList);
                } else {
                    L.i("toshop", "onSlotFail 整个商品出货完成 ");
                    handler.sendEmptyMessage(3);
                }
                L.iTag("SlotCallBac", "onSlotFail  商品出货完成 ");
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    showRightToast("请输入开始货道");
                    break;
                case 1:
                    showRightToast("请输入结束货道");
                    break;
                case 2:
                    showRightToast("请输入要转动的次数");
                    break;
                case 3:
                    isTest = false;
                    removeProgressDialog();
                    showRightToast("所有货道测试完毕");
                    break;
            }
        }
    };
    boolean isTest = false;

    /**
     * 输入选择测试的货道
     */
    private void TestSolt() {
        try {
            String start = startEt.getText().toString();
            String end = endEt.getText().toString();
            String number = numberEt.getText().toString();
            if (start.equals("")) {
                handler.sendEmptyMessage(0);
                HideKeyBoard(this);
                return;
            }
            if (end.equals("")) {
                handler.sendEmptyMessage(1);
                HideKeyBoard(this);
                return;
            }
            if (number.equals("")) {
                handler.sendEmptyMessage(2);
                HideKeyBoard(this);
                return;
            }
            if (intervaldataBeanList.size() > 0) {
                intervaldataBeanList.clear();
            }
            int s = Integer.parseInt(start);
            int e = Integer.parseInt(end);
            if (e<s) {
                showErrorToast("结束货道不能小于开始货道，请重新输入");
                return;
            }

            L.i("检测货道区间 ", s+" 到 "+e);
            for (SlotBean gdb : dataBeanList) {
                if (s <= gdb.getIndex() && gdb.getIndex() <= e) {
                    intervaldataBeanList.add(gdb);
                }
            }
            if (intervaldataBeanList.size() == 0) {
                showErrorToast("起始货道不在机器货道里，请重新输入");
                return;
            }
            L.i("tjf=输完测试的货道=", "输完测试的货道以及转动的次数，点击确定按钮 ");
            showProgressDialog("正在测试所选货道，请等待......", true);
            isTest = true;
            chuhuo();
            ShopInfoUtils.getInstance().setSlotCallBacK(new ShopInfoUtils.SlotCallBacK() {
                @Override
                public void onSlotSuccess(String resultDataStr, byte[] resultBytes) {
                    slotSerialData(resultDataStr, resultBytes);
                    ShopInfoUtils.getInstance().Timercancal();
                    ShopInfoUtils.getInstance().analyzeSlotTest(resultBytes, slotType);
                    L.i("SlotCallBac", "onSlotSuccess  商品出货完成 ==" + resultDataStr);
                    chuhuo();
                }

                @Override
                public void onSlotFail(int slotindex) {
                    for (SlotBean gbs : dataBeanList) {
                        if (gbs.getIndex() == slotindex) {
                            gbs.setTurnNumber(-1);
                        }
                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            slottestAdapter.setData(dataBeanList);
                        }
                    });
                    L.iTag("SlotCallBac", "onSlotFail  商品出货完成 ");
                    chuhuo();
                }
            });
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            isTest = false;

        }
    }

    int count = 0;
    int slotNumber = 0;
    int slotindex = 0;
    int slotType;

    public void chuhuo() {
        String number = numberEt.getText().toString();
        slotNumber = Integer.parseInt(number);
        if (count >= intervaldataBeanList.size()) {
            L.i("tjf==" + "出货结束==");
            handler.sendEmptyMessage(3);
            return;
        }
        handler.post(new Runnable() {
            public void run() {
                slotindex = intervaldataBeanList.get(count).getIndex();
                slotType = intervaldataBeanList.get(count).getSlottypeid();
                ShopInfoUtils.getInstance().TodoShipmentSlot(
                        slotindex, slotType, slotNumber);
                count++;
            }
        });
    }


    public void slotSerialData(String resultDataStr, byte[] resultBytes) {
        // 货道转动完成的返回 10 0E 02 04 01 00 00 01 13 0B 1D 13 0C 05 19 9E
        if (resultBytes[1] >= 0x0E && resultBytes[2] == 0x02) {
            int cabinet = Integer.parseInt(ByteUtils.byteToHex(resultBytes[0])) - 10; // 主副柜
            int aisleNumber = Integer.parseInt(ByteUtils.byteToHex(resultBytes[5]), 16) + 1; // 返回的货道号
            int turnNumber = Integer.parseInt(ByteUtils.byteToHex(resultBytes[7]), 16); // 返回的转动圈数
            aisleNumber = cabinet * 100 + aisleNumber;
            for (SlotBean gbs : dataBeanList) {
                if (gbs.getIndex() == aisleNumber) {
                    if (gbs.getSlottypeid() == 21003) {//区分电磁锁
                        gbs.setTurnNumber(1);
                        break;
                    }
                    if (turnNumber > 0) {
                        gbs.setTurnNumber(1);
                    } else {
                        gbs.setTurnNumber(-1);
                    }
                }
            }
            slottestAdapter.setData(dataBeanList);
            // 主副柜 主柜10开头，副柜1用11开头，副柜2用12开头
            L.i("驱动板出货完成返回：" + resultDataStr,
                    "串口返回的货道号：" + aisleNumber + "\t测试的货道号:" + slotindex,
                    "串口返回的转动圈数：" + turnNumber + "\t需要转动的圈数：" + slotNumber);
            for (int i = 14; i < resultBytes.length - 1; i++) {
                int times = Integer.parseInt(ByteUtils.byteToHex(resultBytes[i]), 16);
                if (times <= 0) {
                    L.i("驱动板出货 转动时间为零  货道号" + aisleNumber);
                    break;
                }
            }
//            int downOnline = Integer.parseInt(ByteUtils.byteToHex(resultBytes[3]), 16); // 掉货检测是否在线
//            int downNumber = Integer.parseInt(ByteUtils.byteToHex(resultBytes[6]), 16); // 检测掉货数量
        }
    }

    /**
     * 隐藏软键盘
     */
    public static void HideKeyBoard(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShopInfoUtils.getInstance().setSlotCallBacK(null);
        slottestAdapter = null;
        dataBeanList.clear();
        dataBeanList = null;
        handler.removeCallbacksAndMessages(null);
        handler = null;
        ShopInfoUtils.dllist.clear();
    }
}
